package com.liuzhilong.infrastructure.basic.proxy.dynamic.cglib;

import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

@Setter
@Accessors(chain = true)
public class SimpleCGLIBProxy<T> implements MethodInterceptor {

    public static  <T> T create(Class<T> tClass){
       return  (T) Enhancer.create(tClass,new SimpleCGLIBProxy());
    }
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println(getClass().getName()+" pre");
        try {
            Object result = methodProxy.invokeSuper(o,objects);
            System.out.println(getClass().getName()+" post");
            return result;
        }catch (Throwable throwable){
            System.out.println(getClass().getName()+" exception");
            throwable.printStackTrace();
            throw throwable;
        }
    }
}
